package com.example.logindb.sevices;


import com.alibaba.fastjson.JSONArray;
import com.example.logindb.entity.Location;
import com.example.logindb.entity.Online;
import com.example.logindb.repository.LocationRepository;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LocationServiceImpl implements LocationService {
    private LocationRepository locationRepository;
    public LocationServiceImpl(LocationRepository locationRepository)
    {
        this.locationRepository = locationRepository;
    }


    @Override
    public void updateLocation(Location location) {
        locationRepository.save(location);
    }

    @Override
    public Location findAllById(Integer id) {
        return locationRepository.findAllByLocid(id);
    }

    @Override
    public List<Location> findAll() {
        return locationRepository.findAll();
    }

    @Override
    public String getAddress(Double lon, Double lat) {

        RestTemplate restTemplate = new RestTemplate();



        String result = restTemplate.getForObject("https://restapi.amap.com/v3/geocode/regeo?output=json&location=" + lon + "," + lat + "&key=be535b01ade695135c7e3b7301f02320", String.class);
        JSONObject root = JSONObject.parseObject(result);

        JSONObject data = root.getJSONObject("regeocode");
        String address = data.getString("formatted_address");
        System.out.println(address);

        return address;

    }

    @Override
    public void deleteLocationById(int id) {
        locationRepository.deleteById(id);
    }

    @Override
    public Location GPSToAMap(Location location) {
        RestTemplate restTemplate = new RestTemplate();
        String result0 = restTemplate.getForObject("https://restapi.amap.com/v3/assistant/coordinate/convert?locations=" + location.getLon() + "," + location.getLat() + "&coordsys=gps&key=be535b01ade695135c7e3b7301f02320", String.class);
        JSONObject root0 = JSONObject.parseObject(result0);
        String locations = root0.getString("locations");
        System.out.println(locations);
        String[] parts = locations.split(",");
        double newLon = Double.parseDouble(parts[0]);
        double newLat = Double.parseDouble(parts[1]);
        Location newLocation = new Location(location.getLocid(), newLat, newLon);
        return newLocation;
    }


}